#!/usr/bin/env python

# MMDS Server Console v0.1

# Adding User to MMDS 


import os

import sys

import hashlib

import md5

import base64

import string

import getpass

import fcntl


# MMDS conf directory


try:

    Conf_dir = os.environ["mmdsDIR"]

except KeyError:

    Conf_dir = os.getcwd()



Ulist_file = os.path.join(Conf_dir, "users.list")

mmdsdpid = os.path.join(Conf_dir, "mmdsd.pid")



def main():

    try:

        if sys.argv[1]:

            uname = sys.argv[1]

    except IndexError:
        uname = get_name()

    check_user(uname)

    hp = get_passwd()

    write_userinfo(uname, hp)

    restart()



def restart():

    try:

        pid = open(mmdsdpid).read()

        pid = string.atoi(pid)

    except (IOError, ValueError):

        pass

    else:

        print "\nSending HUP signal to mmdsd."

        try:

            os.kill(pid, 1)

        except OSError, e:

            sys.stderr.write(e[1] + '\n')

    print "\nUser Successfully Added.\n\n"

    sys.exit()



def get_name():
	
    while 1:

        try:
			
            uname = raw_input("\n\nUsername: ")

        except KeyboardInterrupt:

            sys.stderr.write("\n")

            sys.exit(1)

        if uname == "":

            sys.stderr.write("Username can't be empty.\n")

        else:

            return uname



def get_passwd():

    while 1:

        try:

            passwd = getpass.getpass()

            if passwd == "":

                sys.stderr.write("Password can't be empty.\n")

            else:

                passwd2 = getpass.getpass("Retype password: ")

                if passwd != passwd2:

                    sys.stderr.write("\nPasswords do not match.\n")

                else:

                    hp = base64.encodestring(md5.new(passwd).digest())

                    return hp

        except KeyboardInterrupt:

            sys.stderr.write("\n")

            sys.exit(1)

        

def check_user(uname):

    try:

        fp = open(Ulist_file)

    except IOError:

        pass

    else:

        fcntl.flock(fp.fileno(), fcntl.LOCK_SH)

        userlist = fp.readlines()

        fcntl.flock(fp.fileno(), fcntl.LOCK_UN)

        fp.close()

        for i in xrange(len(userlist)):

            scolon = string.find(userlist[i], ":")

            luname = userlist[i][:scolon]

            if uname == luname:

                sys.stderr.write("User " + uname + " already exists.\n")

                sys.exit(1)



def write_userinfo(uname, hp):

    try:

        fp = open(Ulist_file, "a")

    except IOError, e :

        sys.stderr.write("Can't write to " + Ulist_file + ": " + e[1] + "\n")

        sys.exit(1)

    else:

        fcntl.flock(fp.fileno(), fcntl.LOCK_EX)

        fp.write(uname + ":" + hp)

        fcntl.flock(fp.fileno(), fcntl.LOCK_UN)

        fp.close()

    

os.umask(0066)

main()

